const $config = require('../nuxt.config.js')
const $axios =require('axios'); 
const timeago = require('../lib/timeago');

module.exports = function (Data) {
    // 从Elasticsearch 查询数据 
    // params{
    //     uid:1,
    //     keywords:'tag1',
     //    type:"topic",
    // }
    Data.getDocsBykeywords= async function (params) {
		return await Data.getDocsWithScore(params,0);
	};
    // 
    // [{"name":"united states","score":"12"},{"name":"topic","score":"12"},{"name":"test","score":"12"},{"name":"small ski area","score":"12"},{"name":"ski brule","score":"12"},{"name":"north america","score":"12"}]
    Data.getDocsWithScore= async function ( params,score=1) {
        let mustMatch=[];
        // "filter":[ 
        //     {"term" : { "type" : "topic"}},
        //     {"term" : { "cid" : 3}},
        //     { "exists" : { "field" : "province" }}
        //  ]
        let filter=[
            {"term" : { "deleted" : 0}},
        ];
    
        let shouldmatch=[];
        let keywords = params.keywords;
        // 查类型 {'type':params['type']} // cid Ski Resort 3 , topic 2
        var filterterms =['type','cid','uid','skiResortId',"userCategoryId"]; //允许查询的字段 
        for (const key in params) {
            if(filterterms.indexOf(key)!=-1){
                if(typeof( params[key] )=="string" || typeof( params[key] )=="number"){
                    if(typeof( params[key] )=="string" && params[key].indexOf(">")>-1){
                        filter.push({"range" : { 
                            [key] :{
                                "gt":  params[key].substr(1)
                            } 
                        }});
                    }else if(typeof( params[key] )=="string" && params[key].indexOf("<")>-1){
                        filter.push({"range" : { 
                            [key] :{
                                "lt":params[key].substr(1)
                            } 
                        }});
                    }else{
                        filter.push({"term" : { [key] : params[key]}});
                    }
                }else if( params[key]  instanceof Array && params[key].length>0){
                    filter.push({"terms" : { [key] : params[key]}});
                }
            }
        }
        if(params['cover']==1){
            filter.push({ "exists" : { "field" : "cover" }});
        }
        var mustfiled =['address','tags','title','username','attribute','content','province','city']; //允许查询的字段 
        for (const key in params) {
            if(mustfiled.indexOf(key)!=-1){
                if(typeof( params[key] )=="string" || typeof( params[key] )=="number"){
                    mustMatch.push(
                        { "match": { [key]: params[key] }}
                    );
                }else if( params[key]  instanceof Array && params[key].length>0){
                    mustMatch.push({"match" : { [key] :  params[key].join(",") }});
                }
            }
        }
        
        ////console.log("filterterms :",filter)
        // 给每个词加权重
        if(params['keywords'] && score==1){
            keywords="";
            for (const k in params['keywords']) {
                keywords+=params['keywords'][k].name+",";
                // 查正文
                shouldmatch.push(
                    { "match": {
                        "content": {
                            "query": params['keywords'][k].name,
                            "boost": params['keywords'][k].score
                        }
                    }}
                );
                 // 查标题
                shouldmatch.push(
                    { "match": {
                        "title": {
                            "query": params['keywords'][k].name,
                            "boost": params['keywords'][k].score
                        }
                    }}
                );
                // 查用户名
                shouldmatch.push(
                    { "match": {
                        "username": {
                            "query": params['keywords'][k].name,
                            "boost": params['keywords'][k].score
                        }
                    }}
                );
                
                // 查标签
                shouldmatch.push(
                    { "match": {
                        "tags": {
                            "query": params['keywords'][k].name,
                            "boost": params['keywords'][k].score
                        }
                    }}
                );
            }
        }
        //  { "match": { "type": params['type'] }}
        if( typeof(keywords)=="string" && keywords!="" ){
            mustMatch.push(
                {"multi_match": {
                    "type":     "most_fields", 
                    "query":    keywords,
                    "fields": [ "title", "title.english" ,"description", "description.english" ,"tags", "tags.english","content", "content.english","username", "username.english","location","displayname","aboutme","signature" ],
                    // 'minimum_should_match':"10%",
                    // "tie_breaker":          0.1,
                  }
                }
            );
        }
       
        // let q = {
        //     "query": {
        //         "bool":{}
        //     }
            
        // };
        let q ={
            "query": {
              "function_score": { 
                "query": { 
                    "bool":{

                    }
                },
                "boost_mode":"sum",
                "functions":[],
              }
            }
          }

        //   let script_score = [
        //     {
        //         "script_score": {
        //             "script":"long date = ( new Date().getTime()+1000- doc['timestamp'].value)/(1000*3600*24); double day =  Math.ceil(date);    return ( (1/day)*5*0.4   + (doc['postcount'].value/100) *0.3 + (doc['upvotes'].value/500)*0.2 + (doc['viewcount'].value/1000)*0.1);  "
        //         }
        //     }
        // ];
        //  let script_score = [
        //     {
        //         "script_score": {
        //             "script":"long date = ( new Date().getTime()+1000- doc['timestamp'].value)/(1000*3600*24); double day =  Math.ceil(date);    return ( (1/day)*5*0.4   + (doc['postcount'].value/100) *0.3 + (doc['upvotes'].value/500)*0.2 + (doc['viewcount'].value/1000)*0.1);  "
        //         }
        //     }
        // ];

        let script_score = [
            {
                "script_score": {
                    "script":"0"
                }
            }
        ];

        if(params.type=="topic"){
            q.query.function_score.functions = script_score;
        }
          
          //  timestamp=doc['timestamp'].value
//  postcount=doc['postcount'].value
//  upvotes=doc['upvotes'].value
//  viewcount=doc['viewcount'].value

//  timestamp=1645168022000
//  postcount=0
//  upvotes=0
//  viewcount=0
//  day =  (new Date().getTime() - timestamp)/(1000*3600*24)
//  day = Math.round(day*100)/100
//  if(day==0){
//      day =1
//  }
//  score = (1/day*5*0.4   + postcount/100 *0.3 + upvotes/500*0.2 + viewcount/1000*0.1)
//  println (score)
        //   |(create_time-time())|/1 * 10*0.5  + score + (postcount/10)*0.5  +  (upvotes/10)*0.3 + (viewcount/100)*0.2
        let bool={};  
        if(mustMatch.length>0){
             bool.must=mustMatch;
        }
        if(shouldmatch.length>0){
             bool.should = shouldmatch;
        }
        if(filter.length>0){
            // q.query.bool.filter = filter;
            bool.filter = filter;
        }

        // 排序"sort": { "tid": { "order": "desc" }}
        if(params.sort=="lastposttime"){
            q.sort={
                'lastposttime':{
                     "order" : 'desc'
                }
             }
        }
        q.query.function_score.query.bool = bool
        // q.query.bool = bool;
        if(params.sort=="votes"){
            q.sort={
                'votes':{
                     "order" : 'desc'
                }
             }
        }
        if(params.sort=="postcount"){
            q.sort={
                'postcount':{
                     "order" : 'desc'
                }
             }
        }
       
      
        let res = await Data.getDocs(q,params['size'],params['from']);
        if(res.code>0){
            return res;
        }
        let uids=[];
        res.data.list = res.data.list.map(item => {
            var x = item._source
            uids.push(x.uid);
            // ////console.log("x.tags :",x )
            x.tags =  (typeof(x.tags)=="string" && x.tags!="") ? x.tags.split(",") :[] ;
            if(x.type=="topic"){ 
                x.user = {
                    'icon:bgColor':typeof(x['icon:bgColor'])=="string"?x['icon:bgColor']:'',
                    'picture': x['picture'],
                    'icon:text':typeof(x['icon:text'])=="string"?x['icon:text']:x['username'].substr(0,1).toLocaleUpperCase(),
                    'username':x['username']
                }
            }else{
                x['icon:bgColor']=typeof(x['icon:bgColor'])=="string"?x['icon:bgColor']:'';
                x['icon:text']=typeof(x['icon:text'])=="string"?x['icon:text']:x['username'].substr(0,1).toLocaleUpperCase();
            }
            x.timestamp = timeago(x.timestamp );
            x.lastposttime = x.lastposttime?timeago(x.lastposttime ):x.timestamp;
            // x.province = typeof( x.province)=="string" ? x.province.replaceAll("_"," ") :'';
            if(x.cover){
                x.cover =  x.cover+"?imageView2/1/w/600/h/320" ;
                x.hasCover=1;
            }else{
                x.hasCover=0;
                x.cover = 'https://img.snogogo.com/FpjHSkH8B8zwbrUgASGLsDp0rKDY.png';
            }
           
            if(x.cid==3){
                x.url = "/ski-resort/"+x.slug;
            }else if(x.type=="topic"){
                x.url = "/topic/"+x.slug;
            }else if(x.type=="user"){
                x.url = "/user/"+x.uid;
            }else if(x.type=="post"){
                x.url = "/post/"+x.pid;
            }
            
            return x
         });
       
         let users = await Data.getUserNameAndPictures(uids);
         ////console.log("users:",users);
         res.data.list = res.data.list.map(item => {
            
             if(users[item.uid]){
                item =  Object.assign( item, users[item.uid])
                if(item.user){
                    item.user = Object.assign( item.user, users[item.uid])
                }
             }
             return item;
             
         })
        //  console.log("q",JSON.stringify(q),"res:",JSON.stringify(res))
		return {
            code: res.code,
            msg:res.msg,
            data:res.data
        };
	};
    // get region
    
    // 执行查询
    Data.getDocs= async function (q="",size=10,from=0) {
        console.log("q:", JSON.stringify(q))
        let res = await  $axios.post( $config.elasticsearchHost+'/snogogo/_search?pretty&size='+size+"&from="+from,q)
        if(res.code>0){
            return res;
        }
        // console.log("q:", JSON.stringify(q) ,"Data.getDocs res :", JSON.stringify(res));
        let hits = res.data.hits;
        
        // hits 
        res ={
            code:0,
            data:{
                total:hits.total.value,
                list:hits.hits,
            },
            raw:res.data
        }
		return res;
	};
}